import React, { Component } from "react";
import "./App.css";
export default class App extends Component {
  // 状态数据
  state = {
    todolist: ["吃饭", "睡觉", "打豆豆"],
    userInput: "", //用户在输入框中输入的内容
  };
  doDelete(index) {
    // console.log(index);
    // 从数组中删除下标从index开始的一个元素
    this.state.todolist.splice(index, 1);
    let todolist = this.state.todolist;
    this.setState({ todolist });
  }
  doInputChange = (e) => {
    let userInput = e.target.value;
    this.setState({ userInput });
  };
  doSave = () => {
    // console.log(this.state.userInput)
    //trim: 裁剪输入框前后的空白字符
    if (this.state.userInput.trim() === "") {
      alert("新的代办事项不能为空");
      return;
    }
    // 在数组尾部添加元素
    this.state.todolist.push(this.state.userInput); //仅修改了数据
    let todolist = this.state.todolist;
    this.setState({ todolist, userInput: "" }); //修改数据 + 通知渲染系统
  };
  render() {
    return (
      <div>
        <h2>代办事项列表</h2>
        <hr />
        <input
          value={this.state.userInput}
          onChange={this.doInputChange}
          placeholder="请输入新的待办事项"
        />
        <button onClick={this.doSave}>添加</button>
        {this.state.todolist.length === 0 && <p>您目前暂无代办事项</p>}

        <ol className="list">
          {this.state.todolist.map((item, i) => (
            <li key={i}>
              <span>
                {i + 1} . {item}
              </span>
              <button onClick={() => this.doDelete(i)}>删除</button>
            </li>
          ))}
        </ol>
      </div>
    );
  }
}
